<?php
declare (strict_types=1);

namespace app\common\model;

use app\common\facade\Target;
use app\common\model\Statistics as StatisticsModel;
use think\facade\Cache;
use think\facade\Event;

class ActivityPhoto extends Base
{
    protected $name = 'activity_photo';

    public function user()
    {
        return $this->hasOne(User::class, 'id', 'u_id')->field('id,code,nickname,mobile');
    }

    public function activity()
    {
        return $this->hasOne(Activity::class, 'id', 'a_id');
    }

    public function getStatusAttr($value)
    {
        switch ($value) {
            case 1:
                return '待审核';
            case 2:
                return '已通过';
            case 3:
                return '已驳回';
            default:
                return '未知';
        }
    }


    public static function _save($param, $logs)
    {

        parent::startTrans();
        try {
            if (!isset($param['status'])) return ['code' => -1, 'msg' => '请选择审核类型'];

            $info = parent::find($param['id']);
            if (empty($info)) return ['code' => -1, 'msg' => '审核失败'];
            if ($info->getData('status') != 1) {
                return ['code' => -1, 'msg' => '此笔记录已审核，请勿重复审核！'];
            }
            if ($param['status'] == 2) {
                $msg = '通过激活申请，ID【' . $param['id'] . '】';
                $upload_points = cache('system')['upload_points'];//上传积分
                Target::Account()
                    ->basics($info->u_id, 'integral', $upload_points, '拍照上传', '+')
                    ->lock(false)//写入流水是否上锁，默认false,开启后会大幅降低性能，开启后必须配合事务使用
                    ->createBonus($info->u_id, '3');
                StatisticsModel::_update($upload_points, 'expend');
            } else {
                $msg = '驳回激活申请,ID【' . $param['id'] . '】';
            }

            $info->status = $param['status'];
            if ($param['status'] != 2) {
                $info->reject_msg = $param['reject_msg'];
            }
            $info->admin_id = $logs['admin']->id;
            $info->admin_name = $logs['admin']->admin_name;
            $info->confirm_time = time();
            $info->save();

//            Target::Account()
//                ->basics($user->id, 'coupon', $level->coupon, '激活赠送', '+')
//                ->createNormal($user->id);
            Logs::adds($msg, $logs['admin']->id, $logs['admin']->admin_name);
            parent::commit();
            return ['code' => 1, 'msg' => '已审核'];

        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
}
